package com.wsc.crawler.utils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

// Import Enum
import com.wsc.crawler.Constants.available;

public class InternetConnection {
	static Logger log = Logger.getLogger(InternetConnection.class.getName());

	private static Boolean isNetAvailable(String host) {
		Socket client = null;
		try {
			client = new Socket(host, 53);
			return true;
		} catch (UnknownHostException e) {
			log.warn("Unknown host Exception", e);
		} catch (IOException e) {
			log.warn("IOException While Connecting ", e);
		} finally {
			try {
				if (client != null)
					client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static String isInternetAvialable() {
		String[] hosts = { "8.8.8.8", "8.8.4.4", "208.67.222.222",
				"208.67.220.220" };
		List<Boolean> yes = new ArrayList<Boolean>();

		Boolean[] answers = new Boolean[hosts.length];
		int i = 0;
		for (String host : hosts) {
			answers[i++] = new Boolean(isNetAvailable(host));

		}

		if (answers != null && answers.length > 0) {
			for (Boolean ans : answers) {
				if (ans) {
					yes.add(ans);
				}
			}
			if (yes.size() == hosts.length) {
				return available.yes.name();
			} else if (yes.size() == 0) {
				return available.no.name();
			} else if (yes.size() < hosts.length) {
				return available.no.name();
			}
		}
		return null;
	}

}
